/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.ycl.bk.e2p.ysyb.service;

import cn.ac.iie.di.ban.ycl.bk.e2p.ysyb.main.BanBkE2p;
import cn.ac.iie.di.ban.ycl.bk.e2p.ysyb.tools.fastutil.FastPo;
import cn.ac.iie.di.ban.ycl.bk.e2p.ysyb.tools.JsonUtil;
import cn.ac.iie.di.ban.ycl.bk.e2p.ysyb.tools.fastutil.FileManagerUtil;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;

/**
 *
 * @author wmr
 */
public class FJRThreadTask implements Runnable, Serializable {

    private static Logger logger = Logger.getLogger(FJRThreadTask.class);
    private String jsonFile;
    private String timeout;
    private static String localFilePath;
    String src;
    public static int errorFlag = 0;

    public FJRThreadTask(String jsonFile, String timeout, String localFilePath) {
        this.jsonFile = jsonFile;
        this.timeout = timeout;
        this.localFilePath = localFilePath;
    }

    @Override
    public void run() {
        //解析JSON文件
//        List<String[]> errMsglist = new ArrayList<String[]>();
        logger.info(" start to analyze the JSON file: " + localFilePath + "/" + "Ctrl" + "/" + jsonFile);
        List<Map<String, String>> dataFileList = null;
        boolean analyzeFlag = false;
        try {
            dataFileList = parseJson(localFilePath + "/Ctrl/" + jsonFile, "file_list");
            if (dataFileList.isEmpty()) {
                //错误信息添加进errMsglist
                logger.error(" analyze the JSON file:" + jsonFile + " failed! No file ");
            } else {
                analyzeFlag = true;
            }
        } catch (Exception e) {
            logger.error(" analyze the JSON file:" + jsonFile + " failed!cause: " + e.getMessage(), e);
        }

        String date = null;
        /////////////////////////////////////////
        if (analyzeFlag) {
            String filename = "";
            Map<String, String> str = dataFileList.get(0);
            filename = str.get("name");
            date = filename.substring(1, filename.lastIndexOf("/"));
            logger.info(" upload the data date is: " + date);
        }
        //////////////////////////////////////////
        boolean dwdflag = executeFJRLc(localFilePath + "/Data", BanBkE2p.timeout, dataFileList);
        //生成dwd文件
        if (dwdflag) {
            String nameSpace = localFilePath.substring(localFilePath.lastIndexOf("/") + 1, localFilePath.length());
            String sourceFileType = nameSpace.split("_")[1];
            File file = new File(localFilePath + "/Ctrl/" + jsonFile + "." + sourceFileType + ".dwd");
            try {
                file.createNewFile();
                logger.info("creat dwd file success !!!!!!!!!!! Program execution success");
                logger.info("Program ******************************************** success end");
            } catch (IOException ex) {
                logger.error("creat dwd file failed " + ex.getMessage(), ex);
            }
        } else {

            logger.info("move json to error !!!!!!!!!!! Program execution failed");
            int eflag = FJRThreadTask.errorFlag;

            if (FJRThreadTask.errorFlag == 1 || FJRThreadTask.errorFlag == 2 || FJRThreadTask.errorFlag == 3) {
                String localErrorPath = localFilePath + "/Error/";
                File newErrorPath = new File(localErrorPath);
                //判断文件夹是否存在 
                if (newErrorPath != null && !newErrorPath.exists()) {
                    newErrorPath.mkdirs();
                }

                File jsonF = new File(localFilePath + "/Ctrl/" + jsonFile);
                File okF = new File(localFilePath + "/Ctrl/" + jsonFile + ".ok");

                File jsonFNew = new File(localErrorPath + jsonF.getName());
                jsonF.renameTo(jsonFNew);

                File okFNew = new File(localErrorPath + okF.getName());
                okF.renameTo(okFNew);

            }

        }

        //删除任务
        BanBkE2p.threadList.remove(jsonFile);
        logger.info("Program ******************************************** end");

    }

    public List<Map<String, String>> parseJson(String jsonFile, String nameNode) {
        File file = new File(jsonFile);
        if (file.exists() && file.isFile()) {
            InputStream is = null;
            String jsonString = null;
            try {
                is = new BufferedInputStream(new FileInputStream(file));
                long contentLength = file.length();
                ByteArrayOutputStream outstream = new ByteArrayOutputStream(contentLength > 0 ? (int) contentLength : 1024);
                byte[] buffer = new byte[4096];
                int len;
                while ((len = is.read(buffer)) > 0) {
                    outstream.write(buffer, 0, len);
                }
                outstream.flush();
                outstream.close();
                jsonString = new String(outstream.toByteArray(), "utf-8");
            } catch (FileNotFoundException ex) {
                logger.error(ex.getMessage(), ex);
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                    }
                }
            }
            //parseJsonString
//            JSONObject jsonObject = JSONObject.fromString(jsonString);
            JSONObject jsonObject = JSONObject.fromObject(jsonString);
            src = jsonObject.get("src").toString();
            logger.info("the JSON file " + jsonFile + " src: " + src);
            JSONArray jsonArray = jsonObject.getJSONArray(nameNode);
            List<Map<String, String>> rsList = new ArrayList<Map<String, String>>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject object = (JSONObject) jsonArray.get(i);
                Map<String, String> map = new HashMap<String, String>();
                for (Iterator<?> iter = object.keys(); iter.hasNext();) {
                    String key = (String) iter.next();
                    String value = object.get(key).toString();
                    map.put(key, value);
                    break;
                }
                rsList.add(map);
            }
            logger.info("rsList1 size : " + rsList.size());
            HashSet<Map<String, String>> hashSet = new HashSet<Map<String, String>>(rsList);
            rsList.clear();
            rsList.addAll(hashSet);
            logger.info("rsList2 size : " + rsList.size());
            return rsList;
        } else {
            return null;
        }
    }
    
    public boolean executeFJRLc(String localFilePathData, String timeout, List<Map<String, String>> dataFileList) {
        logger.info(" begin upload files to FastDFS, and the path: " + localFilePath);
        boolean retnrnFlag = true;
        //解析数据描述JSON文件
        logger.info(" begin analyze JSON file, and the path: " + localFilePath);
        boolean jsonDataFlag = new JsonUtil().jsonData(localFilePathData, dataFileList, localFilePath);
        logger.info(" analyze JSON file return " + jsonDataFlag);
        retnrnFlag = jsonDataFlag;
        return retnrnFlag;
    }
    
    public static boolean executeFJR(String localFilePathData, String timeout, List<Map<String, String>> dataFileList) {
        //上传FastDFS
        HashMap<String, FastPo> uploadFastPathMap = null;
        logger.info(" begin upload files to FastDFS, and the path: " + localFilePathData);
        boolean retnrnFlag = true;
        boolean uploadFlag = true;
        try {
            uploadFastPathMap = new FastUploadService().upload(localFilePathData, timeout, dataFileList);
            for (Map.Entry entry : uploadFastPathMap.entrySet()) {
                Object key = entry.getKey();
                FastPo value = (FastPo) entry.getValue();
                if (value.getFilePath().equals("null")) {
                    uploadFlag = false;
                    retnrnFlag = false;
                    logger.info(" upload files to FastDFS failed. uploadFastPathMap size: " + uploadFastPathMap.size() + " upload failed !!!");
                    break;
                }
            }
        } catch (Exception e) {
            logger.info("fastdfs upload failed !!!");
            logger.error(e.getMessage(), e);
            uploadFlag = false;
            retnrnFlag = false;
            return retnrnFlag;
        }

        //解析数据描述JSON文件，并入库
        if (uploadFlag) {
            logger.info(" upload files to FastDFS successfully. uploadFastPathMap size: " + uploadFastPathMap.size() + " upload success");
            logger.info(" begin analyze JSON file and insert data into oracle, and the path: " + localFilePathData + "/" + "Data");
            boolean jsonDataFlag = JsonUtil.jsonData(localFilePathData, dataFileList, localFilePath);

            if (!jsonDataFlag && FJRThreadTask.errorFlag == 1) {
                logger.info("analyze JSON error delete fastfile !!!");
                Iterator<Map.Entry<String, FastPo>> uploadEntries = uploadFastPathMap.entrySet().iterator();
                FileManagerUtil fileManager = new FileManagerUtil();
                while (uploadEntries.hasNext()) {

                    Map.Entry<String, FastPo> uploadEntry = uploadEntries.next();
                    FastPo fastPo = uploadEntry.getValue();
                    String fileAbsolutePath = fastPo.getFilePath();
                    String pangAbsolutePath = fastPo.getPangPath();

                    if (!fileAbsolutePath.equals("null")) {
//                        String fileGroup = fileAbsolutePath.substring(27, 33);
                        logger.info("del fastDataFile start --------------------------");
                        String[] paths = fileAbsolutePath.split("/");
                        String fileGroup = paths[3];
                        logger.info("fileGroup = " + fileGroup);
//                        String errorFilePath = fileAbsolutePath.substring(34, fileAbsolutePath.length());
                        String errorFilePath = "";
                        for (int i = 4; i < paths.length; i++) {
                            errorFilePath += paths[i] + "/";
                        }
                        errorFilePath = errorFilePath.substring(0, errorFilePath.length() - 1);
                        logger.info("filePath = " + errorFilePath);
                        try {
                            fileManager.delFile(fileGroup, errorFilePath);
                            logger.info("del fastDataFile success --------------------------");
                        } catch (Exception ex) {
                            logger.error("delete fast png " + fileAbsolutePath + " error" + ex.getMessage(), ex);
                        }
                        logger.info("del fastDataFile end --------------------------");
                    }
                    if (!pangAbsolutePath.equals("null")) {
                        logger.info("del fastPngFile start --------------------------");
                        String errorPngPath = "";
                        String[] paths = pangAbsolutePath.split("/");
                        String pngGroup = paths[3];
                        logger.info("pngGroup = " + pngGroup);
//                        String errorFilePath = fileAbsolutePath.substring(34, fileAbsolutePath.length());
                        for (int i = 4; i < paths.length; i++) {
                            errorPngPath += paths[i] + "/";
                        }
                        errorPngPath = errorPngPath.substring(0, errorPngPath.length() - 1);
                        logger.info("errorPngPath = " + errorPngPath);
                        try {
                            fileManager.delFile(pngGroup, errorPngPath);
                            logger.info("success del dataFile -----------------------------");
                        } catch (Exception ex) {
                            logger.error("delete fast png " + pangAbsolutePath + " error" + ex.getMessage(), ex);
                        }
                        logger.info("del fastPngFile end --------------------------");
                    }

                    logger.info("Key = " + uploadEntry.getKey() + ", Value = " + uploadEntry.getValue());

                }
//                logger.info(" analyze JSON file and insert data into oracle return " + jsonDataFlag);
                FJRThreadTask.errorFlag = 3;
                logger.info(" analyze JSON file and insert data into oracle error");
            }

            logger.info(" analyze JSON file and insert data into oracle return " + jsonDataFlag);
//            if (jsonDataFlag) {
//                boolean produceDataFlag = false;
//                String returnRocketmq = "";
//                for (String filePath : uploadFastPathMap.values()) {
//                    try {
//                        //发送消息至rocketmq
//                        logger.info(" begin send message to rocketmq, and the filePath is " + filePath);
//                        if (false) {
//                            produceDataFlag = RocketmqUtil.produceData(filePath);
//                        }
//                        produceDataFlag = true;
//                        returnRocketmq = returnRocketmq + produceDataFlag + ",";
//                    } catch (MQClientException ex) {
//                        logger.error(ex.getMessage(), ex);
//                    } catch (InterruptedException ex) {
//                        logger.error(ex.getMessage(), ex);
//                    }
//                }
//            } else {
//                logger.error(" analyze JSON file and insert data into oracle failed ");
//            }
            retnrnFlag = jsonDataFlag;
        }
        return retnrnFlag;
    }

    /**
     * @return the localFilePath
     */
    public String getJsonFile() {
        return jsonFile;
    }

    /**
     * @param localFilePath the localFilePath to set
     */
    public void setJsonFile(String jsonFile) {
        this.jsonFile = jsonFile;
    }

    /**
     * @return the timeout
     */
    public String getTimeout() {
        return timeout;
    }

    /**
     * @param timeout the timeout to set
     */
    public void setTimeout(String timeout) {
        this.timeout = timeout;
    }

    /**
     * @return the localFilePath
     */
    public String getLocalFilePath() {
        return localFilePath;
    }

    /**
     * @param timeout the localFilePath to set
     */
    public void setLocalFilePath(String localFilePath) {
        this.localFilePath = localFilePath;
    }
}
